import {ref, computed} from 'vue';
import {useRoute, useRouter} from 'vue-router';
import {defineStore} from 'pinia';
import {message} from 'ant-design-vue';
import {loginPOST, getInfoGET, logoutPOST} from '@/services/login';
import {getToken, setToken, removeToken} from '@/utils/auth';
import {delay} from '@/utils/delay';
import defAva from '@/assets/images/profile.jpg';
import {store} from './index';

type LoginParams = {
  bodyData: any;
  callback: () => void;
};

export const useUserStore = defineStore('user', () => {
  const route = useRoute();
  const router = useRouter();
  const token = ref<string | undefined>(getToken());
  const userInfo = ref({});
  const roles = ref([]);
  const permissions = ref([]);
  // 登陆
  const login = async ({bodyData, callback}: LoginParams) => {
    try {
      const result = await loginPOST(bodyData);
      console.log('登陆', result);
      if (result) {
        setToken(result.token);
        token.value = result.token;
        await delay(500);
        router.push({path: '/welcome'});
      }
      console.log('登陆响应结果：', result);
      callback && callback();
    } catch (error) {
      await delay(300);
      callback && callback();
    }
  };

  const getUserInfo = async () => {
    const result = await getInfoGET();
    console.log('获取用户信息', result);
    if (result) {
      const user = result.user;
      userInfo.value = user;
      // const avatar =
      //   user.avatar == '' || user.avatar == null ? defAva : import.meta.env.VITE_APP_BASE_API + user.avatar;
      if (result.roles && result.roles.length > 0) {
        // 验证返回的roles是否是一个非空数组
        roles.value = result.roles;
        permissions.value = result.permissions;
      } else {
        roles.value = ['ROLE_DEFAULT'];
      }
    }
  };
  // 退出登陆
  const logOut = async ({msg}: {msg?: string}) => {
    const result = await logoutPOST();
    if (result) {
      removeToken();
      router.push({path: '/login'});
      if (msg) {
        message.error(msg);
      }
    }
  };
  return {userInfo, roles, permissions, login, getUserInfo, logOut};
});
